package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

/*
 * verify access_token token or jwt token
 */
func Auth(ctx iris.Context) {

	if isReqFromAccessTokenSso(ctx) {
		   // access_token token
	} else {
		Jwt(ctx) // jwt token
	}
}

/*
 根据token获取用户id
*/
func GetTokenUserId(Ctx context.Context) (userId string) {
	if isReqFromAccessTokenSso(Ctx) { //access_token


	} else { // jwt
		if Ctx.Values().Get("jwt").(*jwt.Token) == nil || Ctx.Values().Get("jwt").(*jwt.Token).Claims.(jwt.MapClaims) == nil {
			return ""
		}
		userMsg := Ctx.Values().Get("jwt").(*jwt.Token).Claims.(jwt.MapClaims)
		userId = userMsg["user_id"].(string)
	}
	return
}

func GetTokenUId(Ctx context.Context) (Uid float64) {
	if isReqFromAccessTokenSso(Ctx) { //

	} else {
		userMsg := Ctx.Values().Get("jwt").(*jwt.Token).Claims.(jwt.MapClaims)
		Uid = userMsg["Uid"].(float64)
	}
	return
}

// request from access_token sso ?
func isReqFromAccessTokenSso(ctx iris.Context) bool {
	return ctx.GetHeader(`access_token`) != ``
}

func GetUId(Ctx context.Context) uint {
	return uint(GetTokenUId(Ctx))
}

// public return result func
func resp(code int, message, data interface{}, ctx iris.Context) {
	ctx.StopExecution()
	ctx.StatusCode(iris.StatusOK)
	putData := make(map[string]interface{})
	putData["code"] = code
	putData["message"] = message
	putData["data"] = data
	_, _ = ctx.JSON(putData)
	return
}
